﻿using Edu.Http.Extensions;
using Edu.Http.Proxy;
using Infrastructure.Config.Core.External;
using Infrastructure.ExternalService.Core.IdCardNo;
using Infrastructure.ExternalService.Core.IdentityCheck.Request;
using Infrastructure.ExternalService.Core.IdentityCheck.Response;
using Infrastructure.ExternalService.Core.Responses;
using Infrastructure.ExternalService.Core.User;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace Infrastructure.ExternalService.Core.Imp.IdCardNo
{
    public class IdCardNoCheckClient : BaseHttpClient, IIdCardNoCheckClient
    {
        private readonly OrderCenterApiOptions _orderingOptions;

        public IdCardNoCheckClient(IOptions<OrderCenterApiOptions> options, HttpClient client, ILoggerFactory loggerFactory)
            : base(client, loggerFactory, options.Value.ExternalDataOptions.EndPoint)
        {
            _orderingOptions = options.Value ?? throw new HttpProxyException($"{nameof(OrderCenterApiOptions)}配置获取失败");

            loggerFactory.CreateLogger<IdCardNoCheckClient>();
        }

        #region 调用外部数据、免登录、二三要素验证接口
        public async Task<IdentityCheckResopnse> GetExternalDataTwoElementAsync(ExtenalDataIdentityRequest request)
        {
            try
            {
                //0、调用外部数据--二要素验证接口
                var formStr = ConvertRequestToCommonFormUrlEncode(request);
                var response = await GetAsync<WrapResponse<ExtenalDataIdentityResponse>>(_orderingOptions.ExternalDataOptions.IdcardTwoElementIdentify + "?" + formStr);
                //1、无resopnse时，验证异常
                if (response == null)
                {
                    return new IdentityCheckResopnse { Code = "1", Message = "二要素验证异常：无Resopnse" };
                }
                //2、不成功时，验证失败
                if (!response.Success)
                {
                    return new IdentityCheckResopnse { Code = "1", Message = $"二要素验证失败：{response.Msg}" };
                }
                //3、Code!="0000"时，验证失败
                if (response.Code != "0000")
                {
                    return new IdentityCheckResopnse { Code = "1", Message = $"二要素验证失败：{response?.Msg ?? string.Empty}" };
                }
                //4、返回code未0代表通过，1代表不通过
                return new IdentityCheckResopnse { Code = response.Data.Code, Message = response.Data.Message };
            }
            catch (Exception ex)
            {
                return new IdentityCheckResopnse { Code = "1", Message = $"二要素验证接口异常：{ex.Message}" };
            }
        }

        public async Task<IdentityCheckResopnse> GetExternalDataThreeElementAsync(ExtenalDataIdentityRequest request)
        {
            try
            {
                //0、调用外部数据--三要素验证接口
                var formStr = ConvertRequestToCommonFormUrlEncode(request);
                var response = await GetAsync<WrapResponse<ExtenalDataIdentityResponse>>(_orderingOptions.ExternalDataOptions.IdcardThreeElementIdentify + "?" + formStr);
                //1、无resopnse时，验证异常
                if (response == null)
                {
                    return new IdentityCheckResopnse { Code = "1", Message = "三要素验证异常：无Resopnse" };
                }
                //2、不成功时，验证失败
                if (!response.Success)
                {
                    return new IdentityCheckResopnse { Code = "1", Message = $"三要素验证失败：{response.Msg}" };
                }
                //3、Code!="0000"时，验证失败
                if (response.Code != "0000")
                {
                    return new IdentityCheckResopnse { Code = "1", Message = $"三要素验证失败：{response?.Msg ?? string.Empty}" };
                }
                //4、返回code未0代表通过，1代表不通过
                return new IdentityCheckResopnse { Code = response.Data.Code, Message = response.Data.Message };
            }
            catch (Exception ex)
            {
                return new IdentityCheckResopnse { Code = "1", Message = $"三要素验证接口异常：{ex.Message}" };
            }
        }
        #endregion

        #region 调用用户中心、需登录、二三要素验证接口
        public async Task<IdentityCheckResopnse> GetUserCenterTwoElementAsync(UserCenterTwoElementRequest request)
        {
            try
            {
                Dictionary<string, string> headers = new Dictionary<string, string>();
                var ucUser = new
                {
                    ip = request.UserIdentifyIp,
                    ucUser = new
                    {
                        userId = request.UserId,
                        userName = request.UserName
                    }
                };
                headers.Add("ng-expand", JsonConvert.SerializeObject(ucUser));
                //0、调用用户中心--二要素验证接口
                var formStr = ConvertRequestToCommonFormUrlEncode(request);
                base.SetEndPoint(_orderingOptions.UserCenterOptions.EndPoint);
                var response = await PostAsync<WrapResponse<ExtenalDataIdentityResponse>>(_orderingOptions.UserCenterOptions.IdcardTwoElementIdentify + "?" + formStr, headers: headers);
                //1、无resopnse时，验证异常
                if (response == null)
                {
                    return new IdentityCheckResopnse { Code = "1", Message = "二要素验证异常：无Resopnse" };
                }
                //2、不成功时，验证失败
                if (!response.Success)
                {
                    return new IdentityCheckResopnse { Code = "1", Message = $"二要素验证失败：{response.Msg}" };
                }
                //3、Code!="0000"时，验证失败
                if (response.Code != "0000")
                {
                    return new IdentityCheckResopnse { Code = "1", Message = $"二要素验证失败：{response?.Msg ?? string.Empty}" };
                }
                //4、用户中心返回：code=0000且data为null，代表验证成功
                if (response.Code == "0000" && response.Data == null)
                {
                    return new IdentityCheckResopnse { Code = "0", Message = "二要素验证成功！" };
                }

                return new IdentityCheckResopnse { Code = response.Data?.Code ?? "1", Message = response.Data?.Message ?? "二要素验证不通过！" };
            }
            catch (Exception ex)
            {
                return new IdentityCheckResopnse { Code = "1", Message = $"二要素验证接口异常：{ex.Message}" };
            }
        }

        public async Task<IdentityCheckResopnse> GetUserCenterThreeElementAsync(UserCenterThreeElementRequest request)
        {
            try
            {
                Dictionary<string, string> headers = new Dictionary<string, string>();
                var ucUser = new
                {
                    ip = request.Ip,
                    ucUser = new
                    {
                        userId = request.UcUser.UserId,
                        userName = request.UcUser.UserName
                    }
                };
                headers.Add("ng-expand", JsonConvert.SerializeObject(ucUser));
                //0、调用用户中心--二要素验证接口
                var formStr = ConvertRequestToCommonFormUrlEncode(request);
                base.SetEndPoint(_orderingOptions.UserCenterOptions.EndPoint);
                var response = await PostAsync<WrapResponse<UserCenterIdentityResponse>>(_orderingOptions.UserCenterOptions.IdcardThreeElementIdentify + "?" + formStr, headers: headers);
                //1、无resopnse时，验证异常
                if (response == null)
                {
                    return new IdentityCheckResopnse { Code = "1", Message = "三要素验证异常：无Resopnse" };
                }
                //2、不成功时，验证失败
                if (!response.Success)
                {
                    return new IdentityCheckResopnse { Code = "1", Message = $"三要素验证失败：{response.Msg}" };
                }
                //3、Code!="0000"时，验证失败
                if (response.Code != "0000")
                {
                    return new IdentityCheckResopnse { Code = "1", Message = $"三要素验证失败：{response?.Msg ?? string.Empty}" };
                }
                //4、用户中心返回：code=0000且data为null，代表验证成功
                if (response.Code == "0000" && response.Data == null)
                {
                    return new IdentityCheckResopnse { Code = "0", Message = "三要素验证成功！" };
                }

                return new IdentityCheckResopnse { Code = response.Data?.Code ?? "1", Message = response.Data?.Message ?? "三要素验证不通过！" };
            }
            catch (Exception ex)
            {
                return new IdentityCheckResopnse { Code = "1", Message = $"三要素验证接口异常：{ex.Message}" };
            }
        }
        #endregion
    }
}